import { defineStore } from "pinia";
import type { UserInfo } from "@/services/users/types";
import { ref } from "vue";
import { API } from "@/services";
import { useTokenStore } from "../token";
import { Role } from "@/services/users/types";

export const useUserInfoStore = defineStore("userInfo", ()=>{
  const userInfo = ref<UserInfo>({
    username: "",
    account: "",
    detail: {
      email: "",
      phone: "",
    },
  });
  let isInit = false;

  async function dispatchUserInfo() {
    if (isInit) return;
    const tokenStore = useTokenStore();
    await API.users.getUserInfo(tokenStore.token.role, tokenStore.token.id).then((res) => {
      if (res.status === 200) {
        console.log(res.data);
        if (tokenStore.token.role === Role.Student) {
          userInfo.value = {
            username: res.data.student.name,
            account: res.data.student.account,
            role: tokenStore.token.role,
            detail: {
              email: res.data.student.email,
              phone: res.data.student.phoneNumber,
            },
          }
        } else if (tokenStore.token.role === Role.Teacher) {
          userInfo.value = {
            username: res.data.teacher.name,
            account: res.data.teacher.account,
            role: tokenStore.token.role,
            detail: {
              email: res.data.teacher.email,
              phone: res.data.teacher.phoneNumber,
            },
          }
        }
        isInit = true;
      }
    }).catch((err) => {
      console.log(err);
    }
    );
  }

  async function dispatchUpdateUserInfo() {
    const tokenStore = useTokenStore();
    await API.users.getUserInfo(tokenStore.token.role, tokenStore.token.id).then((res) => {
      if (res.status === 200) {
        userInfo.value = {
          username: res.data.student.name,
          account: res.data.student.account,
          role: tokenStore.token.role,
          detail: {
            email: res.data.student.email,
            phone: res.data.student.phoneNumber,
          },
        }
        isInit = true;
      }
    }).catch((err) => {
      console.log(err);
    }
    );
  }

  async function dispatchModify(email:string, phone:string) {
    const tokenStore = useTokenStore();
    await API.users.modifyUserInfo(tokenStore.token.role, tokenStore.token.id, email, phone).then((res) => {
      if (res.status === 200) {
        console.log("修改成功");
      }
    }).catch((err) => {
      console.log(err);
      throw new Error("修改失败" + err);
    });
  }
  return {
    userInfo,
    dispatchUserInfo,
    dispatchUpdateUserInfo,
    dispatchModify,
  }

});
